package com.rx.common.filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rx.common.Constants;
import com.rx.entity.sys.User;

/**
 * 后台过滤器
 * 
 * @author Renxin
 * 
 */
public class AdminFilter implements Filter {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 过滤
	 */
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		logger.debug("[后台过滤地址-开始]");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String ctx = req.getContextPath();
		// 访问地址
		String uri = req.getRequestURI();
		logger.debug("[访问地址:{}]", uri);
		// 如果是登录地址,放行
		if (uri.endsWith(Constants.LOGIN_PATH)) {
			logger.debug("[访问登录地址,通过]");
			chain.doFilter(request, response);
		} else {
			// 用户信息
			User user = (User) req.getSession().getAttribute("user");
			if (user == null) {
				logger.debug("[用户未登录,重定向到登录页]");
				resp.sendRedirect(ctx + Constants.LOGIN_PATH);
			} else {
				String fullUri = uri.substring(uri.indexOf(ctx) + ctx.length());
				// 检查访问地址是否为过滤地址
				if (Constants.ADMIN_FILTER_PATH.contains(fullUri)) {
					logger.debug("[访问地址为过滤地址]");
					Set<String> userUrls = (Set<String>) req.getSession()
							.getAttribute("privilege_url");
					// 检查用户是否拥有访问此地址权限
					if (userUrls.contains(fullUri)) {
						logger.debug("[用户拥有此地址的访问权限,通过]");
						chain.doFilter(request, response);
					} else {
						logger.debug("[用户没有此地址的访问权限]");
						resp.sendRedirect(ctx + Constants.PRIVILEGE_ERROR_PATH);
					}
				} else {
					logger.debug("[访问地址非过滤地址,通过]");
					chain.doFilter(request, response);
				}
			}
		}
		logger.debug("[后台过滤地址-结束]");
	}

	public void destroy() {

	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
